package handlers

import (
	"log"
	"net/http"
	"strconv"

	"excel/database"
	"excel/models"

	"github.com/gin-gonic/gin"
)

// HandleAddTask 处理新增任务请求
func HandleAddTask(c *gin.Context) {
	username := c.GetHeader("X-Username")
	if username == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
		return
	}

	var task models.ExcelData
	if err := c.ShouldBindJSON(&task); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
		return
	}

	// 验证必填字段
	if task.TaskName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "任务名称不能为空"})
		return
	}
	if task.Date == "" || task.Date == "/" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "日期不能为空"})
		return
	}

	// 为空字段设置默认值
	if task.TaskID == "" {
		task.TaskID = "/"
	}
	if task.LiveRoomID == "" {
		task.LiveRoomID = "/"
	}
	if task.StartTime == "" {
		task.StartTime = "/"
	}
	if task.EndTime == "" {
		task.EndTime = "/"
	}
	if task.TaskNature == "" {
		task.TaskNature = "/"
	}
	if task.TaskSource == "" {
		task.TaskSource = "/"
	}
	if task.TaskPriority == "" {
		task.TaskPriority = "/"
	}

	// 插入数据
	_, err := database.DB.Exec(`
		INSERT INTO edata (
			username, task_id, task_name, live_room_id,
			date, start_time, end_time, task_nature,
			task_source, task_priority
		) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		username, task.TaskID, task.TaskName, task.LiveRoomID,
		task.Date, task.StartTime, task.EndTime, task.TaskNature,
		task.TaskSource, task.TaskPriority,
	)

	if err != nil {
		log.Printf("Failed to insert task: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "保存数据失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "添加成功",
	})
}

// HandleUpdateTask 处理更新任务请求
func HandleUpdateTask(c *gin.Context) {
	username := c.GetHeader("X-Username")
	roleStr := c.GetHeader("X-Role")
	if username == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
		return
	}

	role, err := strconv.Atoi(roleStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的角色信息"})
		return
	}

	taskID := c.Param("id")

	var task models.ExcelData
	if err := c.ShouldBindJSON(&task); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
		return
	}

	// 验证必填字段
	if task.TaskName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "任务名称不能为空"})
		return
	}
	if task.Date == "" || task.Date == "/" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "日期不能为空"})
		return
	}

	// 为空字段设置默认值
	if task.TaskID == "" {
		task.TaskID = "/"
	}
	if task.LiveRoomID == "" {
		task.LiveRoomID = "/"
	}
	if task.StartTime == "" {
		task.StartTime = "/"
	}
	if task.EndTime == "" {
		task.EndTime = "/"
	}
	if task.TaskNature == "" {
		task.TaskNature = "/"
	}
	if task.TaskSource == "" {
		task.TaskSource = "/"
	}
	if task.TaskPriority == "" {
		task.TaskPriority = "/"
	}

	// 构建更新SQL
	var query string
	var params []interface{}

	if role >= 10 {
		query = `
			UPDATE edata SET 
				task_id = ?, task_name = ?, live_room_id = ?,
				date = ?, start_time = ?, end_time = ?,
				task_nature = ?, task_source = ?, task_priority = ?
			WHERE id = ?`
		params = []interface{}{
			task.TaskID, task.TaskName, task.LiveRoomID,
			task.Date, task.StartTime, task.EndTime,
			task.TaskNature, task.TaskSource, task.TaskPriority,
			taskID,
		}
	} else {
		query = `
			UPDATE edata SET 
				task_id = ?, task_name = ?, live_room_id = ?,
				date = ?, start_time = ?, end_time = ?,
				task_nature = ?, task_source = ?, task_priority = ?
			WHERE id = ? AND username = ?`
		params = []interface{}{
			task.TaskID, task.TaskName, task.LiveRoomID,
			task.Date, task.StartTime, task.EndTime,
			task.TaskNature, task.TaskSource, task.TaskPriority,
			taskID, username,
		}
	}

	result, err := database.DB.Exec(query, params...)
	if err != nil {
		log.Printf("Failed to update task: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新失败"})
		return
	}

	affected, _ := result.RowsAffected()
	if affected == 0 {
		c.JSON(http.StatusNotFound, gin.H{"error": "未找到要更新的记录或无权限更新"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "更新成功",
	})
}

// HandleDeleteTask 处理删除任务请求
func HandleDeleteTask(c *gin.Context) {
	username := c.GetHeader("X-Username")
	roleStr := c.GetHeader("X-Role")
	if username == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
		return
	}

	role, err := strconv.Atoi(roleStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的角色信息"})
		return
	}

	taskID := c.Param("id")

	var query string
	var params []interface{}

	if role >= 10 {
		query = "DELETE FROM edata WHERE id = ?"
		params = []interface{}{taskID}
	} else {
		query = "DELETE FROM edata WHERE id = ? AND username = ?"
		params = []interface{}{taskID, username}
	}

	result, err := database.DB.Exec(query, params...)
	if err != nil {
		log.Printf("Failed to delete task: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除失败"})
		return
	}

	affected, _ := result.RowsAffected()
	if affected == 0 {
		c.JSON(http.StatusNotFound, gin.H{"error": "未找到要删除的记录或无权限删除"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "删除成功",
	})
}
